package com.it.gw.modules.user.viewmodel

import LoginVo
import android.util.Log
import com.it.common.bean.CommonBean
import com.it.common.livedata.UnPeekLiveData
import com.it.common.utils.MD5Utils
import com.it.common.utils.isNotEmpty
import com.it.data.base.BaseViewModel
import com.it.data.manager.AppCacheManager
import com.it.data.network.Api
import com.it.data.network.req.LoginDto
import com.tencent.mmkv.MMKV

class LoginViewModel : BaseViewModel() {
    val loginLiveData by lazy { UnPeekLiveData<CommonBean<LoginVo>>() }
    val sendCodeLiveData by lazy { UnPeekLiveData<CommonBean<Any>>() }

    /**
     * 登录
     * @param loginName String 用户名
     * @param password String 密码
     */
    fun login(
        loginName: String,
        phone: String,
        password: String?,
        flag: String,
        verifyCode: String?
    ) {
        Log.d(TAG, "login: $loginName $password $flag $verifyCode")
        val dto = LoginDto(
            loginName = loginName,
            phone = phone,
            password = MD5Utils.md5("$password"),
            verifyCode = verifyCode,
            flag = flag,
        )
        if(flag=="1"){
            dto.phone = null
            dto.verifyCode = null
        }
        if(flag=="2"){
            dto.password = null
            dto.loginName = null
        }

        requestCommit(request = {
            Api.apiClient().login(dto)
        }, resp = {
            if (it.result && it.data.isNotEmpty()) {
                MMKV.defaultMMKV().encode(AppCacheManager.KEY_TOKEN, it.data?.token)
                MMKV.defaultMMKV().encode(AppCacheManager.KEY_LOGIN_DATA, it.data)
            }
            loginLiveData.postValue(it)
        })
    }

    fun logout() {
        AppCacheManager.clearAll()

    }

    fun getCode(phone: String) {
        Log.d(TAG, "getCode: ${phone} ")
        requestCommit(request = {
            Api.apiClient().getCode(phone)
        }, resp = {
            sendCodeLiveData.postValue(it)
        })
    }
}